package apk.yoursms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;
import apk.yoursms.ad.ShowAd;
import apk.yoursms.ad.ShowPopUpAndAd;
import apk.yoursms.database.SmsDbHelper;
import apk.yoursms.download.ContentAdapter;
import apk.yoursms.download.DownloadService;
import apk.yoursms.menu.Menu;
import apk.yoursms.settings.ChangeLog;
import apk.yoursms.settings.Settings;
import apk.yoursms.settings.Statistics;
import apk.yoursms.smslist.SmsList;
import apk.yoursms.views.Button;

import com.StarsSDK.StarsSDK;
import com.StarsSDK.Utils.Utils;
import com.flurry.android.FlurryAgent;

public class YourSmsActivity extends TitleBar {

    // private values
    private Menu menu;
    private final String TAG = "apk.yoursms";
    private static ShowPopUpAndAd showRatingAndAd;
    private static boolean showRatingDialog;
    private ContentAdapter contentAdapter;

    private final int SMS_LOVE = 1;
    private final int SMS_SKANDAL = 2;
    private final int SMS_CONG = 3;
    private final int SMS_HUMOR = 4;

    // final int IDD_PROGRESS = 0;
    final int IDD_CLEAR_TABLE = 1;
    final int IDD_ABOUT = 2;
    final static int IDD_RATING = 3;
    final int IDD_EXIT_POPUP = 4;

    // public values
    public static SharedPreferences prefs;
    public static ProgressDialog progressDialog;
    public static ExpandableListView list;
    public static SimplerExpandableListAdapter adapter;
    public static ArrayList<String> titles;
    public static HashMap<Integer, ArrayList<String>> contents;
    public static ArrayList<Integer> catg;
    public static boolean sms_love, sms_skandal, sms_congratulations,
	    sms_humor;
    public static String lang;
    public static boolean showAnyDialog = false;
    public static Intent service;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	try {
	    PackageInfo info = getPackageManager().getPackageInfo(
		    getPackageName(), 0);
	    StarsSDK.init(getPackageName(), this, info.versionCode);
	} catch (NameNotFoundException e) {
	    Log.d(TAG, "Error in packageInfo and init SDK");
	    e.printStackTrace();
	}

	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.mainlist);

	Statistics.idEvent = 0;
	progressDialog = new ProgressDialog(this);
	menu = new Menu(this, getLayoutInflater());
	ChangeLog cl = new ChangeLog(this);
	if (cl.firstRun()) {
	    cl.getLogDialog().show();
	}
	showAnyDialog = false;
	contentAdapter = new ContentAdapter(this);

	service = new Intent(this, DownloadService.class);
	registerReceiver(broadcastReceiver, new IntentFilter(
		DownloadService.BROADCAST_ACTION));
    }

    /** Called when the activity is started. */
    @Override
    public void onStart() {
	super.onStart();
	setContentView(R.layout.mainlist);
	FlurryAgent.onStartSession(this,
		getString(R.string.flurry_publisher_id));

	prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
	showRatingAndAd = new ShowPopUpAndAd(prefs);
	if (showRatingDialog && showAnyDialog) {
	    showDialog(IDD_RATING);
	    showRatingDialog = false;
	}

	sms_love = prefs.getBoolean("sms_love", false);
	sms_skandal = prefs.getBoolean("sms_skandal", false);
	sms_congratulations = prefs.getBoolean("sms_congratulations", false);
	sms_humor = prefs.getBoolean("sms_humor", false);
	lang = prefs.getString("lang", "default");

	list = new ExpandableListView(this);
	list.setGroupIndicator(null);
	list.setChildIndicator(null);
	list.setCacheColorHint(0);

	catg = new ArrayList<Integer>();

	int i = 0;
	titles = new ArrayList<String>();
	contents = new HashMap<Integer, ArrayList<String>>();
	if (sms_love) {
	    ArrayList<String> content = getList(Values.SMS_LOVE);
	    if (content != null) {
		titles.add(getString(R.string.sms_love));
		contents.put(i++, content);
	    }
	}
	if (sms_skandal) {
	    ArrayList<String> content = getList(Values.SMS_SKANDAL);
	    if (content != null) {
		titles.add(getString(R.string.sms_skandal));
		contents.put(i++, content);
	    }
	}
	if (sms_congratulations) {
	    ArrayList<String> content = getList(Values.SMS_CONG);
	    if (content != null) {
		titles.add(getString(R.string.sms_congratulations));
		contents.put(i++, content);
	    }
	}
	if (sms_humor) {
	    ArrayList<String> content = getList(Values.SMS_HUMOR);
	    if (content != null) {
		contents.put(i++, content);
		titles.add(getString(R.string.sms_humor));
	    }
	}

	Log.d("YOUR SMS ACTIVITY", String.valueOf(titles));
	Log.d("YOUR SMS ACTIVITY", String.valueOf(contents));

	adapter = new SimplerExpandableListAdapter(this, titles, contents);
	list.setAdapter(adapter);

	list.setOnChildClickListener(new OnChildClickListener() {
	    public boolean onChildClick(ExpandableListView parent, View v,
		    int groupPosition, int childPosition, long id) {
		Statistics.setData(String.valueOf(groupPosition)
			+ String.valueOf(childPosition));
		hideMenu();

		Intent intent = null;
		if (showAdDialog()) {
		    intent = new Intent(YourSmsActivity.this, ShowAd.class);
		} else {
		    intent = new Intent(YourSmsActivity.this, SmsList.class);
		}

		intent.putExtra("name_child",
			adapter.getChild(groupPosition, childPosition));

		startActivity(intent);
		return false;
	    }
	});
	LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
		LinearLayout.LayoutParams.FILL_PARENT,
		LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);

	LinearLayout layout = (LinearLayout) findViewById(R.id.mainlist);
	list.setLayoutParams(lParams);
	layout.addView(list);

	if (!(sms_love || sms_skandal || sms_congratulations || sms_humor)) {
	    setContentView(R.layout.main);
	}

    }

    private void updateBase() {
	if (!catg.isEmpty()) {
	    service.putIntegerArrayListExtra("catg", catg);
	    startService(service);
	}
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
	@Override
	public void onReceive(Context context, Intent intent) {
	    updateUI(intent);
	}
    };

    private void updateUI(Intent intent) {
	int ctg = intent.getExtras().getInt("ctg");
	contentAdapter.updateList(ctg);

	adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
	super.onDestroy();
	unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onPause() {
	super.onPause();
    }

    @Override
    public void onStop() {
	super.onStop();
	FlurryAgent.onEndSession(this);
    }

    @Override
    public void onResume() {
	super.onResume();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
	super.onConfigurationChanged(newConfig);
    }

    private ArrayList<String> getList(String category) {
	ArrayList<String> list = new ArrayList<String>();
	ArrayList<String> arrayCtg = new ArrayList<String>();

	Cursor cursor = getContentResolver().query(
		Uri.parse("content://apk.yoursms.database.SmsProvider/"
			+ getString(R.string.tableName)), null,
		SmsDbHelper.SMS_CATEGORY + "=" + category, null, null);
	cursor.moveToFirst();

	if (cursor.getCount() != 0) {
	    do {
		String c = cursor.getString(1);
		if (!arrayCtg.contains(c)) {
		    arrayCtg.add(c);
		}
	    } while (cursor.moveToNext());
	    cursor.close();

	    for (String l : arrayCtg) {
		list.add(l);
	    }
	    return list;

	} else {
	    cursor.close();
	    catg.add(Integer.valueOf(category));

	    if (isServiceRunning()) {
		try {
		    return getFullList(category);
		} catch (IOException e) {
		    e.printStackTrace();
		    Log.d("YOUR SMS ACTIVITY", "DOWNLOAD FROM FILE EXCEPTION");
		    return null;
		}
	    }
	    return null;
	}
    }

    private boolean isServiceRunning() {
	ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	for (RunningServiceInfo service : manager
		.getRunningServices(Integer.MAX_VALUE)) {
	    if ("apk.yoursms.download.DownloadService".equals(service.service
		    .getClassName())) {
		return true;
	    }
	}
	return false;
    }

    private boolean hideMenu() {
	if (menu.isShow) {
	    menu.hide();
	    return true;
	}
	return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_MENU) {
	    if (!hideMenu()) {
		menu.show(findViewById(R.id.title));
	    }
	    return true;
	} else if (keyCode == KeyEvent.KEYCODE_BACK) {
	    if (!hideMenu()) {
		exit();
	    }
	    return true;
	} else if (keyCode == KeyEvent.KEYCODE_HOME) {
	    Statistics.setData("YourSmsActivity Home Click");
	    hideMenu();
	    return true;
	} else
	    return super.onKeyDown(keyCode, event);
    }

    private void exit() {
	hideMenu();

	if ((isMarketAvailable(this))
		&& (Utils.isOnline())
		&& !(Utils.isPackageInstalled("com.StarsApplications.Scramble"))) {
	    showDialog(IDD_EXIT_POPUP);
	} else {
	    finish();
	}

    }

    @Override
    protected Dialog onCreateDialog(int id) {
	switch (id) {
	case IDD_CLEAR_TABLE:
	    AlertDialog.Builder builder = new AlertDialog.Builder(
		    YourSmsActivity.this);
	    builder.setMessage(getString(R.string.clear_table_question))
		    .setCancelable(false)
		    .setPositiveButton(getString(R.string.clear_table_yes),
			    new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
					int id) {

				    YourSmsActivity.this
					    .getContentResolver()
					    .delete(Uri
						    .parse("content://apk.yoursms.database.SmsProvider/"
							    + getString(R.string.tableName)),
						    null, null);

				    prefs.edit().putBoolean("sms_love", false)
					    .commit();
				    prefs.edit()
					    .putBoolean("sms_skandal", false)
					    .commit();
				    prefs.edit()
					    .putBoolean("sms_congratulations",
						    false).commit();
				    prefs.edit().putBoolean("sms_humor", false)
					    .commit();
				    onStart();
				}
			    })
		    .setNegativeButton(getString(R.string.clear_table_no),
			    new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
					int id) {
				    dialog.cancel();
				}
			    });
	    return builder.create();

	case IDD_ABOUT:
	    final Dialog dialog = new Dialog(YourSmsActivity.this);
	    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    dialog.setContentView(R.layout.about_layout);
	    dialog.setCancelable(true);

	    Button button = (Button) dialog.findViewById(R.id.Button01);
	    button.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
		    dialog.cancel();
		}
	    });

	    dialog.show();
	    return dialog;
	case IDD_RATING:
	    Statistics.setData("Show Rating Dialog");
	    final Dialog dialog_rating = new Dialog(YourSmsActivity.this);
	    dialog_rating.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    dialog_rating.setContentView(R.layout.rating_layout);
	    dialog_rating.setCancelable(false);

	    button = (Button) dialog_rating.findViewById(R.id.Button01);
	    button.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
		    dialog_rating.cancel();
		}
	    });

	    Button btnRtg = (Button) dialog_rating.findViewById(R.id.Button02);
	    btnRtg.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
		    onRate(null);
		    if (Utils.isOnline())
			dialog_rating.cancel();
		}
	    });

	    dialog_rating.show();
	    return dialog_rating;
	case IDD_EXIT_POPUP:
	    final Dialog dialogExit = new Dialog(YourSmsActivity.this);
	    dialogExit.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    dialogExit.setContentView(R.layout.exit_layout);
	    dialogExit.setCancelable(true);

	    Button skipBtn = (Button) dialogExit.findViewById(R.id.skipBtn);
	    skipBtn.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
		    dialogExit.cancel();
		    finish();
		}
	    });

	    Button downloadBtn = (Button) dialogExit
		    .findViewById(R.id.getAppBtn);
	    downloadBtn.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
		    try {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri
				.parse("market://details?id=com.StarsApplications.Scramble"));
			startActivity(intent);
		    } catch (Exception e) {
			Toast.makeText(YourSmsActivity.this, R.string.error,
				Toast.LENGTH_LONG).show();
		    }

		}
	    });

	    dialogExit.show();
	    return dialogExit;
	default:
	    return null;
	}
    }

    public void handlerButton(View view) {
	switch (view.getId()) {
	case R.id.menu_settings:
	    hideMenu();
	    Statistics.setData("Settings");
	    Intent intent = new Intent(getBaseContext(), Settings.class);
	    startActivity(intent);
	    break;

	case R.id.menu_download:
	    hideMenu();
	    Statistics.setData("Update Base");
	    //	    if (Utils.isOnline()) {

	    YourSmsActivity.this.getContentResolver().delete(
		    Uri.parse("content://apk.yoursms.database.SmsProvider/"
			    + getString(R.string.tableName)), null, null);
	    onStart();
	    updateBase();
//	    } else {
//		Toast.makeText(YourSmsActivity.this,
//			R.string.should_connection, Toast.LENGTH_LONG).show();
//	    }

	    break;

	case R.id.menu_clear:
	    hideMenu();
	    Statistics.setData("Clear Base");
	    showDialog(IDD_CLEAR_TABLE);
	    break;

	case R.id.menu_about:
	    hideMenu();
	    Statistics.setData("About Dialog");
	    showDialog(IDD_ABOUT);
	    break;

	case R.id.menu_exit:
	    exit();
	    break;

	}
    }

    @Override
    public void onRate(View v) {
	super.onRate(v);
    }

    boolean isMarketAvailable(Context context) {
	Intent intent = new Intent();
	intent.setAction(Intent.ACTION_VIEW);
	intent.setData(Uri.parse("market://search?q=foo"));
	PackageManager pm = context.getPackageManager();
	List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);

	boolean installed = !(list == null || list.isEmpty());

	return installed;
    }

    public static void showRatingDialog() {
	if (!prefs.getBoolean("show_rating", false)
		&& showRatingAndAd.needShowRating()) {
	    showRatingDialog = true;
	    showAnyDialog = true;
	} else {
	    showRatingDialog = false;
	}
    }

    public static boolean showAdDialog() {
	if (Utils.isOnline() && showRatingAndAd.needShowAd()) {
	    return true;
	}

	return false;
    }

    public static SharedPreferences getPrefs() {
	return prefs;
    }

    private ArrayList<String> getFullList(String ctg) throws IOException {
	String file = null;
	ArrayList<String> list = new ArrayList<String>();
	switch (Integer.valueOf(ctg)) {
	case SMS_LOVE:
	    file = Values.SMS_LOVE_FILE;
	    break;

	case SMS_SKANDAL:
	    file = Values.SMS_SKANDAL_FILE;
	    break;

	case SMS_CONG:
	    file = Values.SMS_CONG_FILE;
	    break;

	case SMS_HUMOR:
	    file = Values.SMS_HUMOR_FILE;
	    break;

	default:
	    break;
	}

	String path = getString(R.string.local) + "/" + file;

	InputStream stream = null;
	try {
	    stream = getAssets().open(path);
	} catch (IOException e) {
	}

	BufferedReader dataStream = new BufferedReader(new InputStreamReader(
		stream, "UTF8"));
	String data = "";
	try {
	    while ((data = dataStream.readLine()) != null) {
		data = (data.contains("&web") ? data.split("&web")[0] : data);
		list.add(data);
		dataStream.readLine();
	    }

	} catch (Exception e) {
	    runOnUiThread(new Runnable() {
		public void run() {
		    Toast.makeText(getApplicationContext(), "Oooops",
			    Toast.LENGTH_SHORT).show();
		}
	    });
	}

	stream.close();
	dataStream.close();
	return list;
    }

}
